package com.xuan.common.security.interceptor;

import cn.hutool.core.collection.CollUtil;
import com.xuan.common.core.constants.Constants;
import com.xuan.common.core.constants.HttpConstants;
import com.xuan.common.core.utils.ThreadLocalUtils;
import com.xuan.common.security.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;    //从哪个服务的配置文件中读取，取决于这个bean对象交给了哪个服务的spring容器进行管理。


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从 Http 请求头中获取 token 并解析
        // 2. 通过得到的 userKey 从redis中获取缓存数据
        // 3. 如果缓存没有过期，且满足一定的条件则为用户令牌续期
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if (StringUtils.isBlank(token)) {
            return true;
        }
        Claims claims = tokenService.getClaims(token, secret);
        if (claims == null) {
            return true;
        }
        Long userId = tokenService.getUserId(claims);
        String tokenKey = tokenService.getTokenKey(claims);
        ThreadLocalUtils.set(Constants.USER_ID, userId);
        ThreadLocalUtils.set(Constants.USER_KEY, tokenKey);
        tokenService.extendToken(claims);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除 ThreadLocal 存储的 userId 和 userKey
        if (!ThreadLocalUtils.mapIsNull()) {
            ThreadLocalUtils.set(Constants.USER_ID, null);
            ThreadLocalUtils.set(Constants.USER_KEY, null);
        }

    }

}
